package cn.zc.student.service.service.impl;

import cn.tools.core.exception.BizException;
import cn.tools.dozer.config.DozerUtils;
import cn.zc.student.entity.Dto.StudentUserDto;
import cn.zc.student.entity.StudentUser;
import cn.zc.student.entity.VO.StudentUserVO;
import cn.zc.student.service.mapper.StudentUserMapper;
import cn.zc.student.service.service.RoleService;
import cn.zc.student.service.service.StudentAndClassifyService;
import cn.zc.student.service.service.StudentUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 学生用户表 服务实现类
 * </p>
 *
 * @author keno
 * @since 2022-02-23
 */
@Service
public class StudentUserServiceImpl extends ServiceImpl<StudentUserMapper, StudentUser> implements StudentUserService {

    @Resource
    private DozerUtils dozerUtils;

    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Resource
    private StudentAndClassifyService studentAndClassifyService;

    @Resource
    private RoleService roleService;

    /**
     * 注册学生用户
     * @param studentUserDto
     */
    @Override
    public void createStudentUser(StudentUserDto studentUserDto) {
        StudentUser one = getOne(new QueryWrapper<StudentUser>().lambda().eq(StudentUser::getUserName, studentUserDto.getUserName()));
        if(one != null){
            throw new BizException("用户名重复，请重新设置用户名");
        }

        StudentUser student = dozerUtils.map(studentUserDto, StudentUser.class);

        student.setUserPassword(bCryptPasswordEncoder.encode(student.getUserPassword()));

        if(!save(student)){
            throw new BizException("注册用户失败");
        }
    }



    /**
     * 学生用户密码登录
     * @param userName
     * @param passWord
     * @return
     */
    @Override
    public StudentUserVO studentPasswordLogin(String userName, String passWord) {

        StudentUser one = getOne(new QueryWrapper<StudentUser>().lambda().eq(StudentUser::getUserName, userName));
        if(one == null){
            throw new BizException("用户名不存在");
        }
        if(!bCryptPasswordEncoder.matches(passWord,one.getUserPassword())){
            throw new BizException("密码错误");
        };
        StudentUserVO student = dozerUtils.map(one, StudentUserVO.class);
        student.setStudentAndClassifyVO(studentAndClassifyService.findClassify(one.getId()));
        student.setRole(roleService.getRole(one.getId()));

        return student;
    }
}
